package cn.mianshiyi.braumclient.config;

import cn.mianshiyi.braumclient.utils.EasyStringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;

/**
 * @author shangqing.liu
 */
@Configuration
public class DistRedisClientFactory {

    @Value("${easy.limiter.dist.redis.host:#{null}}")
    private String distRedisHost;

    @Value("${easy.limiter.dist.redis.port:#{null}}")
    private Integer distRedisPort;

    @Value("${easy.limiter.dist.redis.password:#{null}}")
    private String distRedisPassword;

    private static JedisPool jedisPool;

    @Bean
    public JedisPool init() {
        if (EasyStringUtil.isEmpty(distRedisHost)) {
            return null;
        }
        //获取数据，设置到JedisPoolConfig中
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(20);
        config.setMaxIdle(10);
        config.setMinIdle(5);
        config.setBlockWhenExhausted(true);
        config.setMaxWaitMillis(3000);
        config.setTestWhileIdle(true);
        //初始化JedisPool
        jedisPool = new JedisPool(config, distRedisHost, distRedisPort == null ? RateLimiterConfig.DIST_DEFAULT_REDIS_PORT : distRedisPort, Protocol.DEFAULT_TIMEOUT, distRedisPassword);
        return jedisPool;
    }

    public static Jedis getJedis() {
        if (jedisPool == null) {
            return null;
        }
        return jedisPool.getResource();
    }

    public static void close(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}
